package com.wmlive.hhvideo.common.base;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.WindowCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.bugtags.library.Bugtags;
import com.umeng.analytics.MobclickAgent;
import com.wmlive.hhvideo.application.AppStatusManager;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.common.MyAppActivityManager;
import com.wmlive.hhvideo.heihei.beans.login.MobileLoginResponse;
import com.wmlive.hhvideo.heihei.channel.ISinaLoginView;
import com.wmlive.hhvideo.heihei.channel.IWechatLoginView;
import com.wmlive.hhvideo.heihei.channel.LoginSinaChannelPresenter;
import com.wmlive.hhvideo.heihei.channel.LoginWechatChannelPresenter;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.login.LoginDialog;
import com.wmlive.hhvideo.heihei.mainhome.activity.MainNewActivity;
import com.wmlive.hhvideo.heihei.websocket.WebSocketServiceManager;
import com.wmlive.hhvideo.utils.DeviceUtils;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.WeakHandler;
import com.wmlive.hhvideo.widget.dialog.CustomProgressDialog;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.wmlive.hhvideo.R;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by lsq on 5/27/2017.
 * Activity基类，不含根布局
 */
public abstract class BaseCompatActivity<P extends IBasePresenter>
        extends AppCompatActivity
        implements View.OnClickListener, BaseView, EasyPermissions.PermissionCallbacks, IWechatLoginView, ISinaLoginView {

    private Set<IBasePresenter> presenterList = new HashSet<>();

    public final String requestTag = getClass().getSimpleName();
    protected P presenter;
    private WeakHandler weakHandler;
    private long lastClickTime;
    private int lastViewId;//上次点击的控件Id
    private Unbinder unbinder;
    //    private LoadingDialog loadingDialog;
    private CompositeDisposable compositeDisposable;
    private LoginWechatChannelPresenter loginWechatChannelPresenter;
    private LoginSinaChannelPresenter loginSinaChannelPresenter;
    private LoginDialog loginDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        switch (AppStatusManager.getInstance().getAppStatus()) {
            //应用被强杀
            case AppStatusManager.STATUS_FORCE_KILLED:
                protectApp();
                break;
            //应用正常启动,在splashactivity中设置
            case AppStatusManager.STATUS_NORMAL:
            default:
                if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
                    finish();
                    return;
                }
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_MODE_OVERLAY);  //防止在WebView中长按复制出现标题栏显示错误
                KLog.i("############_" + requestTag + "_onCreate");
                int layoutId = getLayoutResId();
                if (layoutId > 0) {
                    setContentView(layoutId);
                }
                initBaseView();
                unbinder = ButterKnife.bind(this);
                presenter = getPresenter();
                addPresenter(presenter);
                initData();
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    MyAppActivityManager.getInstance().pushActivity(this);
                }
                break;
        }
    }

    /**
     * 控制statusbar和toolbar的显示
     *
     * @param status 0：正常显示toolbar和statubar
     *               1：隐藏toolbar，显示statubar
     *               2：隐藏toolbar和statubar
     *               3：显示toolbar，内容沉浸到statubar（5.0以上有效）
     *               4：隐藏toolbar，内容沉浸到statubar（5.0以上有效）
     */
    protected void changeDecorView(int status) {
        int option = 0;
        switch (status) {
            case 0:
                option = View.SYSTEM_UI_FLAG_VISIBLE;
                break;
            case 1:
                option = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
                break;
            case 2:
                if (Build.VERSION.SDK_INT >= 16) {
                    option = View.SYSTEM_UI_FLAG_FULLSCREEN;
                }
                break;
            case 3:
            case 4:
                if (Build.VERSION.SDK_INT >= 21) {
                    option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                }
                break;
        }
        getWindow().getDecorView().setSystemUiVisibility(option);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(status == 3 || status == 4 ?
                    Color.TRANSPARENT : getResources().getColor(R.color.colorPrimaryDark));
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            if (status == 4 || status == 2 || status == 1) {
                actionBar.hide();
            } else {
                actionBar.show();
            }
        }
        if (status == 3) {
            AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
            if (null != appBarLayout) {
                RelativeLayout.LayoutParams l = (RelativeLayout.LayoutParams) appBarLayout.getLayoutParams();
                l.topMargin = DeviceUtils.getStatusBarHeight(this);
            }
        }
    }

    /**
     * 弹Toast并且关闭页面
     */
    protected void toastFinish() {
        showToast(R.string.hintErrorDataDelayTry);
        finish();
    }

    /**
     * 安全地弹toast
     *
     * @param stringId
     */
    protected void showToast(int stringId) {
        showToast(getString(stringId));
    }

    /**
     * 安全地弹toast
     *
     * @param message
     */
    protected void showToast(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtil.showToast(message);
            }
        });
    }

    /**
     * 获取一个WeakHandler，用来替换Handler
     *
     * @return
     */
    protected WeakHandler getWeakHandler() {
        if (weakHandler == null) {
            weakHandler = new WeakHandler();
        }
        return weakHandler;
    }


    @Override
    protected void onStart() {
        super.onStart();
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.start();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        KLog.i("==========" + requestTag + "——onResume");
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.resume();
            }
        }
        Bugtags.onResume(this);
        MobclickAgent.onPageStart(requestTag);
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        KLog.i("==========" + requestTag + "——onPause");
        Bugtags.onPause(this);
        MobclickAgent.onPageEnd(requestTag);
        MobclickAgent.onPause(this);
        DeviceUtils.hiddenKeyBoard(findViewById(android.R.id.content));
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.pause();
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Bugtags.onDispatchTouchEvent(this, ev);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onStop() {
        super.onStop();
        KLog.i("==========" + requestTag + "onStop");
        for (IBasePresenter presenter : presenterList) {
            if (null != presenter) {
                presenter.stop();
            }
        }
    }

    @Override
    protected void onDestroy() {
        removeWeakHandler();
        Iterator<IBasePresenter> iterator = presenterList.iterator();
        while (iterator.hasNext()) {
            iterator.next().destroy();
            iterator.remove();
        }
        closeLoadingDialog();
        if (unbinder != null) {
            unbinder.unbind();
        }
        KLog.i("==========" + requestTag + "_onDestroy");
        super.onDestroy();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            MyAppActivityManager.getInstance().popActivity(this);
        }
    }

    /**
     * 移除weakHandler的消息
     */
    public void removeWeakHandler() {
        if (weakHandler != null) {
            weakHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 添加Presenter
     *
     * @param presenters
     */
    protected void addPresenter(IBasePresenter... presenters) {
        for (IBasePresenter presenter : presenters) {
            if (null != presenter) {
                presenter.bindContext(this);
                presenterList.add(presenter);
            }
        }
    }

    /**
     * 初始化presenter，只针对泛型方式传入的Presenter
     *
     * @return
     */
    protected P getPresenter() {
        return null;
    }

    /**
     * 初始化基础布局，Base之间的继承才调用这个方法，其他情况不用
     */
    void initBaseView() {

    }


    /**
     * 初始化数据
     */
    protected void initData() {
        loginWechatChannelPresenter = new LoginWechatChannelPresenter(this);
        loginSinaChannelPresenter = new LoginSinaChannelPresenter(this);
        addPresenter(loginWechatChannelPresenter, loginSinaChannelPresenter);
    }

    public void showReLogin() {
        if (loginDialog == null) {
            loginDialog = new LoginDialog(this);
            loginDialog.setOnLoginClick(new LoginDialog.OnLoginClick() {
                @Override
                public void loginWeChartClick() {
                    loading();
                    loginWechatChannelPresenter.WXLogin();
                }

                @Override
                public void loginSinaClick() {
                    loading();
                    loginSinaChannelPresenter.SinaLogin();
                }
            });
        }
        if (!loginDialog.isShowing()) {
            loginDialog.show();
        }

    }

    /**
     * 显示一个正在进行的操作的Dialog
     *
     * @param message
     * @param cancelable
     */
    public void showLoadingDialog(final String message, boolean cancelable) {
//        closeLoadingDialog();
//        if (loadingDialog == null) {
//            loadingDialog = new LoadingDialog(this);
//        }
//        loadingDialog.setCancelable(cancelable).setMessage(message).show();
    }

    /**
     * 关闭正在操作的Dialog
     */
    public void closeLoadingDialog() {
//        if (loadingDialog != null) {
//            loadingDialog.dismiss();
//            loadingDialog = null;
//        }
    }

    @Override
    public void onClick(View v) {
        long currentTime = System.currentTimeMillis();
        if ((lastViewId == v.getId())) {
            if (currentTime - lastClickTime > GlobalParams.Config.MINIMUM_CLICK_DELAY) {
                onSingleClick(v);
            } else {
                KLog.i(requestTag, "快速点击无效");
            }
        } else {
            onSingleClick(v);
        }
        lastViewId = v.getId();
        lastClickTime = currentTime;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBack();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void onBack() {
        int count = getFragmentManager().getBackStackEntryCount();
        if (count > 0) {
            getFragmentManager().popBackStack();
        } else {
            onBackPressed();
        }
    }

    /**
     * view的点击事件都在此方法中处理
     *
     * @param v
     */
    protected abstract void onSingleClick(View v);

    /**
     * 返回当前activity的布局id
     *
     * @return
     */
    protected abstract int getLayoutResId();


    /**
     * 安全地启动一个隐式Intent
     * 打开相机的隐式Intent，如果系统相机应用被关闭或者不存在相机应用，
     * 又或者是相机应用的某些权限被关闭等等情况都可能导致这个隐式的Intent无法正常工作
     *
     * @param intentName
     */
    protected void startActivity(String intentName) {
        Intent intent = new Intent(intentName);
        ComponentName componentName = intent.resolveActivity(getPackageManager());
        if (componentName != null) {
            startActivity(intent);
        } else {
            showToast("无法启动相应的组件");
        }
    }


    /**
     * 请求的url错误
     */
    @Override
    public void handleNetError() {
        ToastUtil.showToast(R.string.net_error);
    }

    /**
     * 请求的返回结果错误
     *
     * @param requestCode
     * @param message
     */
    @Override
    public void onRequestDataError(int requestCode, String message) {
        showToast(message);
    }

    //====================检测用户是否登录========================


    //======================权限检查===========================

    public PermissionCallbackInterface permissionCallbackInterface;

    public void checkPermissionsStatus(String[] params, PermissionCallbackInterface callbackInterface) {
        if (params == null || params.length == 0) {
            return;
        }
        permissionCallbackInterface = callbackInterface;
        if (EasyPermissions.hasPermissions(this, params)) {
            //权限都授权了
            if (permissionCallbackInterface != null) {
                permissionCallbackInterface.onPermissionsHasCallback();
            }
        } else {
            //申请权限
            EasyPermissions.requestPermissions(this, getResources().getString(R.string.request_some_permissions), 0, params);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //把申请权限的回调交由EasyPermissions处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        //授权的
        if (permissionCallbackInterface != null) {
            permissionCallbackInterface.onPermissionsGrantedCallback(requestCode, perms);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        //未授权
        if (permissionCallbackInterface != null) {
            permissionCallbackInterface.onPermissionsDeniedCallback(requestCode, perms);
        }
    }

    @Override
    public void handleWechatLoginSucceed(final MobileLoginResponse response) {
        dismissLoad();
        if (null != loginDialog) {
            loginDialog.dismiss();
        }
        AccountUtil.resetAccount(response);
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(Integer integer) throws Exception {
                        AccountUtil.updateUserInfo(response);
                        return true;
                    }
                }).subscribe();
        ToastUtil.showToast(R.string.login_suc);
        //登录成功，重新启动websocket 服务
        WebSocketServiceManager.getInstance(DCApplication.getDCApp()).reStartWebSocketService();
        //切换数据库
        IMMessageUserDBManager.switchUserDBManager(DCApplication.getDCApp());
        //删除临时数据库
        IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp()).delImDefaultEntryAll();
    }

    @Override
    public void handleWechatLoginFailure(String error_msg) {
        dismissLoad();
        ToastUtil.showToast(error_msg);
    }

    @Override
    public void handleSinaLoginSucceed(final MobileLoginResponse response) {
        dismissLoad();
        if (null != loginDialog) {
            loginDialog.dismiss();
        }
        AccountUtil.resetAccount(response);
        Observable.just(1)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, Boolean>() {
                    @Override
                    public Boolean apply(Integer integer) throws Exception {
                        AccountUtil.updateUserInfo(response);
                        return true;
                    }
                }).subscribe();
        ToastUtil.showToast(R.string.login_suc);
        //登录成功，重新启动websocket 服务
        WebSocketServiceManager.getInstance(DCApplication.getDCApp()).reStartWebSocketService();
        //切换数据库
        IMMessageUserDBManager.switchUserDBManager(DCApplication.getDCApp());
        //删除临时数据库
        IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp()).delImDefaultEntryAll();
    }

    @Override
    public void handleSinaLoginFailure(String error_msg) {
        dismissLoad();
        ToastUtil.showToast(error_msg);
    }

    //权限回调接口
    public interface PermissionCallbackInterface {
        void onPermissionsHasCallback();

        void onPermissionsGrantedCallback(int requestCode, List<String> params);

        void onPermissionsDeniedCallback(int requestCode, List<String> params);
    }

    public CustomProgressDialog customProgressDialog;

    public void loading() {
        loading(true, null);
    }

    public CustomProgressDialog loading(boolean cancelable, DialogInterface.OnDismissListener listener) {
        if (null == customProgressDialog) {
            customProgressDialog = new CustomProgressDialog(this);
        }
        customProgressDialog.setOnDismissListener(listener);
        customProgressDialog.setCancelable(cancelable);
        customProgressDialog.loading();
        return customProgressDialog;
    }

    public void dismissLoad() {
        if (null != customProgressDialog) {
            customProgressDialog.dismiss();
        }
        customProgressDialog = null;
    }

    protected void protectApp() {
        Intent intent = new Intent(this, MainNewActivity.class);
        intent.putExtra(AppStatusManager.KEY_HOME_ACTION, AppStatusManager.ACTION_RESTART_APP);
        startActivity(intent);
    }
}
